package org.app.data.temp;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EnJSON {
	char ch[];
	int id;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	/**
	 * 转换 自定义 类
	 * 
	 * @param type
	 * @return
	 */
	public <T> T toBean(Class<T> clazz) {
		T t = null;

	//	StringBuffer sb = new StringBuffer();
		try {

			if (ch[id] == '{') {
				t = clazz.newInstance();

				id++;
				// toBean(t);
				BeanInfo bean = Introspector.getBeanInfo(t.getClass());
				PropertyDescriptor[] pds = bean.getPropertyDescriptors();

				int size = pds.length - 1;
				for (int i = 0; i < size; i++) {
					// toBean(t);

					String name = fromJson();
					Object value = null;
					id++; // :

					PropertyDescriptor pd = new PropertyDescriptor(name,
							t.getClass());
					Class type = pd.getPropertyType();
					if (ch[id] == '{') {// ||ch[id]PropertyDescriptor=='['

						if (type.isAssignableFrom(Map.class)) {
							Class gener = this.getType(name, clazz);// 泛型
							Map map = new HashMap();
							toBean(map, gener);// name,
							value = map;
						} else
							value = toBean(type);
					} else if (ch[id] == '[') {
						Class gener = this.getType(name, clazz);// 泛型
						List list = new ArrayList();
						toBeans(list, gener);
						if (type.isArray()) {
							value = this.toArray(list, gener);
						} else {
							value = list;
						}
					} else
						value = fromJson();

					pd.getWriteMethod().invoke(t, value);

					System.out.println("char" + ch[id]);
					if (ch[id] == '}') {
						id++;// 跳过'}'
						break;
					}
				}
			}

		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// System.out.println(t);
		return t;
	}

	

	protected String fromJson() {// char[] ch
		StringBuffer sb = new StringBuffer();

		while (id < ch.length) {
			if (ch[id] == '\"' || ch[id] == ',' || ch[id] == '{'
					|| ch[id] == '}' || ch[id] == ']') {
				if (sb.length() != 0) {
					id++;//
					return sb.toString();
				}
			} else {
				sb.append(ch[id]);
			}
			id++;
		}
		return sb.toString();
	}



	/**
	 * 数组
	 * @param gener
	 * @return
	 */
	public <T>T[] toBeans(Class<T> gener){
		List list=new ArrayList();
		toBeans(list,gener);
		for(Object o:list){
			System.out.println(o+":"+o.getClass());
		}
		return this.toArray(list, gener);
	}
	
	/**
	 * []
	 * 暂分 Array 数组 和 List 列表
	 * @param list
	 * @param type
	 */
	public <T> void toBeans(List list, Class<T> type) {
		// List list =new ArrayList();
		if (ch[id] == '[') {
			id++;
		}

		if (ch[id] == '{') {
			// id++;
			while (id < ch.length) {
				list.add(toBean(type));
				// id=id+2;//,{
				if (ch[id] == ']')
					break;
				id++;
			}
		}else{
			while(id<ch.length){
			//	if(type.isAssignableFrom(Number.class))
				
				list.add(fromJson());
				if(ch[id-1]==']'||ch[id]==']')break; //[1,3,5] 对于数值数组 由于没有“，最后会跳过],返回字符串数组
			}
		}

		// return list;
	}
	
	

	/**
	 * 考虑 Map {*:{#:#}} {#:#}
	 * 
	 * @param map
	 * @param name
	 * @param type
	 */
	public <T> void toBean(Map map, Class<T> type) {// String name,

		if (ch[id] == '{') {

			while (id < ch.length) {

				String name = fromJson();
				id++;// :
				Object value = null;
				if (ch[id] == '{') {
					value = toBean(type);
				} else {
					value = fromJson();
				}
				map.put(name, value);
				if (ch[id] == '}')
					break;
				id++;
			}
		}

		// return list;
	}

	protected <T> T[] toArray(List list, Class<T> type) {// ,PropertyDescriptor pd

		T[] t = (T[]) Array.newInstance(type, list.size());
		list.toArray(t);
//		for (Object obj : t) {
//			System.out.println(obj);
//		}
	//	System.out.println(t.getClass());
		return t;
	}
	
	public Class getType(String name, Class type) {// 泛型 ，嵌套 泛型等
		if (type == Object.class)
			return type;
		Class clazz = null;
		try {
			Field f = type.getDeclaredField(name);
			Type typ = f.getGenericType();

			if (typ instanceof ParameterizedType) {// 泛型
			//	System.out.println("泛型");
				ParameterizedType pt = (ParameterizedType) typ;
				Type[] ts = pt.getActualTypeArguments();

				clazz = (Class) ts[ts.length - 1]; // 对于 Map型 只 考虑 Type[1]
													// ；不处理嵌套泛型
			}

			else {
				clazz = (Class) typ;
			//	System.out.print(clazz.isArray());

				if (clazz.isArray()) {
					//System.out.println("Array:");
					clazz = clazz.getComponentType();// /
				}
			}

		//	System.out.println("type:" + clazz);
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			return getType(name, type.getSuperclass());
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return clazz;
	}
	
	public void setJSON(String temp) {
		ch = temp.toCharArray();
		id = 0;
	}

}
